package server.core;

import server.*;
import server.connector.http.HttpRequestImpl;
import server.connector.http.HttpResponseImpl;

import javax.servlet.ServletException;
import java.io.IOException;

//简单管道
public class SimplePipeline implements Lifecycle {
    //基本阀
    protected Valve basic = null;
    //管道所在的容器
    protected Container container = null;
    //其他阀
    private Valve[] valves = new Valve[0];

    public SimplePipeline(Container container) {
        setContainer(container);
    }

    //添加阀
    public void addValve(Valve valve) {
        if (valve instanceof Contained)
            ((Contained)valve).setContainer(container);
        synchronized (valves) {
            Valve[] newValves = new Valve[valves.length + 1];
            System.arraycopy(valves, 0, newValves, 0, valves.length);
            newValves[valves.length] = valve;
            valves = newValves;
        }
    }

    public void invoke(HttpRequestImpl request, HttpResponseImpl response) throws IOException, ServletException {
        (new SimplePipelineValveContext()).invokeNext(request, response);
    }
    //getter------------------------------------------------------------------------------

    public Valve getBasic() {
        return basic;
    }
    public Valve[] getValves() {
        return this.valves;
    }

    //setter------------------------------------------------------------------------------
    public void setContainer(Container container) {
        this.container = container;
    }
    public void setBasic(Valve valve) {
        this.basic = valve;
        ((Contained)valve).setContainer(container);
    }

    protected class SimplePipelineValveContext implements ValveContext {
        //执行到了第几个阀(从1开始)
        protected int stage = 0;
        @Override
        public String getInfo() {
            return null;
        }

        @Override
        public void invokeNext(HttpRequestImpl request, HttpResponseImpl response) throws IOException, ServletException {
            int index = stage++;
            if (index < valves.length) {
                valves[index].invoke(request, response, this);
            } else if (index == valves.length && basic != null) {
                basic.invoke(request, response, this);
            } else {
                throw new ServletException("No valve");
            }
        }
    }

    //实现Lifecycle接口-------------------------------------------------------------------------
    @Override
    public void addLifecycleListener(LifecycleListener listener) {

    }

    @Override
    public LifecycleListener[] findLifecycleListeners() {
        return null;
    }

    @Override
    public void removeLifecycleListener(LifecycleListener listener) {

    }

    @Override
    public void start() throws LifecycleException {

    }

    @Override
    public void stop() throws LifecycleException {

    }
}
